<?php
namespace App;

use JMS\Serializer\Serializer;
use JMS\Serializer\SerializerBuilder;

class UserSerializer
{

    private Serializer $serializer;

    public function __construct()
    {
        $this->serializer = SerializerBuilder::create()
            //->setCacheDir(__DIR__ . '/../cache')
            //->setDebug(true)
            ->build();
    }

    public function serialize(): void
    {
        $user = new User();
        $user->name = 'liuyibao';
        $user->mobile = '15900610000';

        $log = new UserLog();
        $log->id = 1;
        $log->time = '2020-12-03 12:00:05';
        $log->address = '上海';
        $user->logs[] = $log;

        $log = new UserLog();
        $log->id = 2;
        $log->time = '2020-12-03 13:40:05';
        $log->address = '上海市';
        $user->logs[] = $log;

        $str = $this->serializer->serialize($user, 'json');
        echo $str;
    }

    public function unSerialize(): void
    {
        $jsonStr = <<<EOF
{"name":"liuyibao","mobile":"15900610000","logs":[{"id":1,"time":"2020-12-03 12:00:05","address":"\u4e0a\u6d77"},{"id":2,"time":"2020-12-03 13:40:05","address":"\u4e0a\u6d77\u5e02"}]}
EOF;
        $object = $this->serializer->deserialize($jsonStr, User::class, 'json');

        var_dump($object);

    }
}